package com.tlsy.commerce.multi_tenant;

import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * @author Tlsy
 * @version commerce 0.0.1
 * @date 2017/4/10  18:20
 */
public class MultiTenantJpaTransactionManager extends JpaTransactionManager {
    private static final long serialVersionUID = 7905529138996160688L;

    @Override
    protected void doBegin(Object transaction, TransactionDefinition definition) {
        super.doBegin(transaction, definition);
        final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                .getResource(getEntityManagerFactory());
        final EntityManager em = emHolder.getEntityManager();
        final Serializable tenantId = TenantHolder.getTenant();
        if (tenantId != null) {
            em.setProperty(TenantHolder.TENANT_ID, tenantId);
        }

    }
}
